﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace MCYFlashApp
{

    public class XmlFile
    {
        private string _filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "flashfile");
        private string _xmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "play.xml");
        private string _xmlAutoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "autoplay.xml");

        private List<SwfFile> _lstFiles = new List<SwfFile>();
        private List<SwfFile> _lstAutoFiles = new List<SwfFile>();
        public List<SwfFile> LstFiles
        {
            get
            {
                return _lstFiles.OrderBy(p => p.FileName).ToList();
            }
        }

        public List<SwfFile> LstAutoFiles
        {
            get { return _lstAutoFiles; }
        }

        private List<SwfFile> _lstAddFile = new List<SwfFile>();
        private List<SwfFile> _lstDelFile = new List<SwfFile>();

        public void InitFile()
        {
            List<SwfFile> deleFile = new List<SwfFile>();
            _lstFiles.Clear();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(_xmlPath);

            var elements = xmlDoc.SelectNodes("PlayFiles/File");
            for (int i = 0; i < elements.Count; i++)
            {
                SwfFile file = new SwfFile();
                XmlElement xe = (XmlElement)elements.Item(i);
                if (xe.HasChildNodes)
                {
                    file.FileName = xe.ChildNodes.Item(0).InnerText;

                    file.FileExtension = xe.ChildNodes.Item(1).InnerText;
                    file.FilePath = xe.ChildNodes.Item(2).InnerText;
                    if (File.Exists(file.FilePath))
                        _lstFiles.Add(file);
                    else
                        deleFile.Add(file);
                }
            }

            DeleteFromXml(deleFile);


            XmlDocument xmlAutoDoc = new XmlDocument();
            xmlAutoDoc.Load(_xmlAutoPath);

            elements = xmlAutoDoc.SelectNodes("PlayFiles/File");
            for (int i = 0; i < elements.Count; i++)
            {
                SwfFile file = new SwfFile();
                XmlElement xe = (XmlElement)elements.Item(i);
                if (xe.HasChildNodes)
                {
                    file.FileName = xe.ChildNodes.Item(0).InnerText;

                    file.FileExtension = xe.ChildNodes.Item(1).InnerText;
                    file.FilePath = xe.ChildNodes.Item(2).InnerText;
                    file.Index = int.Parse(xe.ChildNodes.Item(3).InnerText);
                    if (File.Exists(file.FilePath))
                        _lstAutoFiles.Add(file);

                }
            }
        }

        public void ScanFiles()
        {
            _lstAddFile.Clear();
            //_lstDelFile.Clear();
            _lstFiles.Clear();
            GetDirFile(_filePath);

            ReflashXml();
        }

        private void GetDirFile(string path)
        {
            if (Directory.Exists(path))
            {
                string[] dirs = Directory.GetDirectories(path);
                if (dirs != null)
                {
                    foreach (string dir in dirs)
                    {
                        DirectoryInfo dirinfo = new DirectoryInfo(dir);
                        foreach (var file in dirinfo.GetFiles())
                        {
                            if (file.Extension != ".swf" && file.Extension != ".exe") continue;
                            if (file.Extension == ".exe" && file.Name.Contains("Srv")) continue;
                            if (file.Extension == ".exe" && file.Name.Equals("flashShell.exe")) continue;
                            var find = _lstFiles.Find(p => file.Name.Contains(dirinfo.Name));
                            if (find == null)
                            {
                                SwfFile newfile = new SwfFile();
                                newfile.FileExtension = file.Extension;
                                newfile.FilePath = file.FullName;
                                newfile.FileName = dirinfo.Name;
                                _lstFiles.Add(newfile);
                                _lstAddFile.Add(newfile);
                            }

                        }
                    }
                }
            }
        }

        private void AddFile(FileInfo file)
        {
            if (file.Extension != ".swf" && file.Extension != ".exe") return;
            var find = _lstFiles.Find(p => file.Name.Contains(p.FileName));
            if (find == null)
            {
                SwfFile newfile = new SwfFile();
                newfile.FileExtension = file.Extension;
                newfile.FilePath = file.FullName;
                newfile.FileName = file.Name.Replace(file.Extension, "");
                _lstFiles.Add(newfile);
                _lstAddFile.Add(newfile);
            }

        }

        private void GetFile(string path)
        {
            if (Directory.Exists(path))
            {
                string[] dirs = Directory.GetDirectories(path);
                if (dirs != null)
                {
                    foreach (string dir in dirs)
                    {

                    }
                }

                string[] files = Directory.GetFiles(path);
                if (files != null)
                {
                    foreach (var file in files)
                    {
                        AddFile(new FileInfo(file));
                    }
                }
            }
            //如果路径是文件，添加到list
            else if (File.Exists(path))
            {
                AddFile(new FileInfo(path));
            }

        }

        private void ReflashXml()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(_xmlPath);

            XmlNodeList xmlFile = xmlDoc.SelectNodes("PlayFiles/File");
            for (int i = 0; i < xmlFile.Count; i++)
            {
                xmlFile[i].ParentNode.RemoveChild(xmlFile[i]);
            }
            foreach (SwfFile file in _lstAddFile)
            {
                CreateNode(xmlDoc, file);
            }
            xmlDoc.Save(_xmlPath);
        }

        private void DeleteFromXml(List<SwfFile> files)
        {
            if (files.Count == 0) return;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(_xmlPath);

            foreach (var iten in files)
            {
                DeleteSingNode(xmlDoc, iten.FileName);
            }

            xmlDoc.Save(_xmlPath);
        }

        private void CreateNode(XmlDocument xmlDoc, SwfFile file)
        {

            XmlElement xmlfile = xmlDoc.CreateElement("File");
            XmlElement xmlShortName = xmlDoc.CreateElement("FileName");
            xmlShortName.InnerText = file.FileName;
            xmlfile.AppendChild(xmlShortName);

            XmlElement xmlFileName = xmlDoc.CreateElement("FileExt");
            xmlFileName.InnerText = file.FileExtension;
            xmlfile.AppendChild(xmlFileName);

            XmlElement xmlFilePath = xmlDoc.CreateElement("FilePath");
            xmlFilePath.InnerText = file.FilePath;
            xmlfile.AppendChild(xmlFilePath);

            XmlElement xmlIndex = xmlDoc.CreateElement("Index");
            xmlIndex.InnerText = file.Index.ToString();
            xmlfile.AppendChild(xmlIndex);

            var root = xmlDoc.DocumentElement;//取到根结点
            //添加为根元素的第一层子结点
            root.AppendChild(xmlfile);

        }

        private void DeleteNode(string fileName)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(_xmlPath);



            DeleteSingNode(xmlDoc, fileName);

            xmlDoc.Save(_xmlPath);
        }

        private void DeleteSingNode(XmlDocument xmlDoc, string fileName)
        {
            var root = xmlDoc.DocumentElement;//取到根结点
            var elements = xmlDoc.SelectSingleNode("PlayFiles/File").ChildNodes;
            for (int i = 0; i < elements.Count; i++)
            {
                XmlElement xe = (XmlElement)elements.Item(i);
                if (xe.FirstChild.InnerText.Equals(fileName))
                {
                    root.RemoveChild(xe);
                    break;
                }
            }
        }


        public void ReflashAutoXml(List<SwfFile> lst)
        {
            try
            {
                if (File.Exists(_xmlAutoPath))
                    File.Delete(_xmlAutoPath);
                //创建XmlDocument对象
                XmlDocument xmlDoc = new XmlDocument();
                //XML的声明<?xml version="1.0" encoding="gb2312"?> 
                XmlDeclaration xmlSM = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                //追加xmldecl位置
                xmlDoc.AppendChild(xmlSM);
                //添加一个名为Gen的根节点
                XmlElement xml = xmlDoc.CreateElement("", "PlayFiles", "");
                //追加Gen的根节点位置
                xmlDoc.AppendChild(xml);

                foreach (SwfFile file in lst)
                {
                    CreateNode(xmlDoc, file);
                }
                xmlDoc.Save(_xmlAutoPath);


            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }
    }
}
